package com.hktf.corelib.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;


public class CRCUtils {


    public static String formatCRC32(long code) {
        return addPrefix0(Long.toHexString(code));
    }

    private static String addPrefix0(String code) {
        String pcode = "00000000" + code;
        return pcode.substring(pcode.length() - 8);
    }


    public static String getCRC32(String src) {
        CRC32 crc32 = new CRC32();
        crc32.update(src.getBytes());
        String code = Long.toHexString(crc32.getValue()).toString();
        return addPrefix0(code);
    }


    public static String getCRC32(InputStream inputStream) {
        CRC32 crc32 = new CRC32();
        CheckedInputStream checkedinputstream = null;
        String crc = null;
        try {
            checkedinputstream = new CheckedInputStream(inputStream, crc32);
            while (checkedinputstream.read() != -1) {
            }
            crc = Long.toHexString(crc32.getValue());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (checkedinputstream != null) {
                try {
                    checkedinputstream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return addPrefix0(crc);
    }


    public static String getCRC32(File file) {
        FileInputStream stream = null;
        String code = "";
        try {
            stream = new FileInputStream(file);
            code = getCRC32(stream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return code;
    }
}
